package com.springboot.common.mybatis.intercept;

import com.springboot.util.TenantThreadLocal;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.util.Properties;

/**
 * @Author: TongRui乀
 * @Date: 2019-11-15 15:44
 * @description：
 */
@Component
@Intercepts(value = {
                 @Signature(type = StatementHandler.class,
                        method = "prepare",
                        args = {Connection.class,Integer.class})})
public class TenantIntercept implements Interceptor {

    private static final String preState="/*!mycat:datanode=";

    private static final String afterState="*/";

    private Logger logger = LoggerFactory.getLogger(TenantIntercept.class);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        StatementHandler statementHandler=(StatementHandler)invocation.getTarget();
        MetaObject metaStatementHandler=SystemMetaObject.forObject(statementHandler);
        Object object=null;
        //分离代理对象链
        while(metaStatementHandler.hasGetter("h")){
            object=metaStatementHandler.getValue("h");
            metaStatementHandler= SystemMetaObject.forObject(object);
        }
        String sql=(String)metaStatementHandler.getValue("delegate.boundSql.sql");

        // 获取租户唯一标识
        String node = TenantThreadLocal.get();

        if(node!=null) {
            sql = preState + node + afterState + sql;
        }

        logger.info("拼接之后的SQL：{}", sql);

        metaStatementHandler.setValue("delegate.boundSql.sql",sql);

        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {

        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        String prop1 = properties.getProperty("prop1");
        String prop2 = properties.getProperty("prop2");
        System.out.println(prop1 + "------" + prop2);
    }
}
